package com.tank.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.tank.bean.User;
import com.tank.dao.UserDAO;
import com.tank.util.ImageCut;
import com.tank.util.TankUtil;

@Controller
@Scope("prototype")

public class FaceAction extends ActionSupport {

	File face;
	String faceFileName;
	String faceContentType;
	
	User author;

	@Resource(name="userDao")
	UserDAO dao;
	
	public File getFace() {
		return face;
	}

	public void setFace(File face) {
		this.face = face;
	}

	public String getFaceFileName() {
		return faceFileName;
	}

	public void setFaceFileName(String faceFileName) {
		this.faceFileName = faceFileName;
	}

	public String getFaceContentType() {
		return faceContentType;
	}

	public void setFaceContentType(String faceContentType) {
		this.faceContentType = faceContentType;
	}

	public User getAuthor() {
		return author;
	}

	public void setAuthor(User author) {
		this.author = author;
	}
	
	@Override
	public String execute() throws Exception {
		
		
		System.out.println(author.getId());
		
		
		String rpath=ServletActionContext.getServletContext().getRealPath("zgg/face/");
		
		faceFileName=author.getId()+this.getFaceFileName().substring(getFaceFileName().lastIndexOf("."));
		
		System.out.println(faceFileName);
		rpath=rpath+'/'+faceFileName;
		File save=new File(rpath);
		System.out.println(save.getPath());
		System.out.println(rpath);
//		System.out.println(face.getPath());
//		InputStream is=new FileInputStream(face);
//		OutputStream os=new FileOutputStream(save);
//		byte[] buff=new byte[1024];
//		int len=0;
//		while( (len=is.read(buff)) != -1){
//			os.write(buff, 0, len);
//		}
//		
//		os.close();
//		is.close();
		
		ImageCut.scale(face.getPath(), save.getPath(), 100, 100);
		
		author=dao.findUserById(author.getId());
		author.setPhoto("zgg/face/"+faceFileName);
		dao.update(author);
		ServletActionContext.getRequest().getSession().setAttribute("user",author);
		
		return SUCCESS;
	}
	
	
	

}
